#include "main.h"
//遍历存储至链表
struct Plink*my_plink(FILE*F)
{
	//创建头节点
	struct Plink*PP=malloc(sizeof(struct Plink));
	if(PP==NULL){printf("创建头节点失败\n");return NULL;}
	PP->len=0;PP->Next=NULL;
	//读取文件内信息,存储至链表
	struct Plink t={0,NULL};
	printf("%s\n",t.loginn.name);
	fseek(F,0,0);
	while(fscanf(F,"账号:%s 密码:%s \n",t.loginn.name,t.loginn.password)!=EOF)
	{
		printf("读取成功\n");
		printf("账号:%s  密码:%s\n",t.loginn.name,t.loginn.password);
		//sleep(2);
		struct Plink*p1=malloc(sizeof(struct Plink));
		if(p1==NULL){printf("节点创建失败\n");return NULL;}
		memcpy(p1->loginn.name,t.loginn.name,20);
		memcpy(p1->loginn.password,t.loginn.password,20);
		p1->Next=PP->Next;
		PP->Next=p1;
		PP->len++;
	}
	return PP;
}
//遍历查找                               
int my_login(struct Plink*P,struct login C_login)
{
	struct Plink* t=P->Next;
	int n=P->len;
	//printf("%d\n",P->len);
	while(n>0)
	{
		//printf("对比\n");
		//printf("账号：%20s  密码：%20s\n",t->loginn.name,t->loginn.password);
		if(strcmp(t->loginn.name,C_login.name)==0)
		{
	//		printf("账号存在\n");
			if(strcmp(t->loginn.password,C_login.password)==0)
			{
	//			printf("密码正确\n");
				return 0;
			}
		}
		t=t->Next;
		n--;
	}
	return -1;
}
///////////////////////////////////多线程服务器端
	extern int S;
	extern int n;
	extern int C[3];
	extern struct login C_login[3];
	extern struct Plink *P;
void*create_server(void*arg)
{
	int i=*(int*)arg;
	n++;
	//4、阻塞等待客户端请求
	printf("阻塞等待客户端%d请求\n",i);
	if((C[i]=accept(S,NULL,NULL))==-1){perror("与客户端建立连接失败");return NULL;}
	//printf("与%d建立连接成功\n",i);
	//客户端登录信息
	int ret;
	while(1)
	{
	//	printf("接收客户端登录数据\n");
		if(read(C[i],&C_login[i],sizeof(C_login[i]))==0){printf("客户端%d断开连接\n",i);return NULL;}
	//	printf("接收客户端%d登陆数据完成\n",i);
		ret=my_login(P,C_login[i]);
	//	printf("反馈客户端%d登录结果\n",i);
		write(C[i],&ret,4);
		if(ret==0)
		{
			printf("客户端<%d>登录成功\n",i);
			break;
		}
	}
	//
	while(1)
	{
		struct pack txt={0};
		if(read(C[i],(char*)&txt,8)==0){printf("读取客户端<%d>协议包失败\n",i);break;}
	//	printf("接收客户端%d聊天数据大小为%d\n",i,txt.packsize);
		read(C[i],(char*)&txt.date,txt.packsize);
		printf("接收客户端聊天数据:<%d> ->> <%d>:%s\n",i,txt.client,txt.date);
		int to=txt.client;
		txt.client=i;
		write(C[to],(char*)&txt,txt.packsize+8);
				
	}
	return NULL;
}
//
///////////////////////////////////多线程客户端
void*create_client(void*arg)
{
	while(1)
	{
		struct pack read_txt={0};
		int client=*(int*)arg;
	//	printf("等待服务器数据\n");
		if(read(client,&read_txt,8)==0){printf("服务器断开连接\n");break;}
	//	printf("接收数据\n");
		read(client,&read_txt.date,read_txt.packsize);
		printf("远端发送:<%d>  ->> :%s\n",read_txt.client,read_txt.date);
	}
}
